﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using RuoVea.ExDto;
using System.Security.Claims;

namespace RuoVea.Report.Web.Filters;

public class GlobalAuthorizeFilter : IAuthorizationFilter
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
        if (actionDescriptor != null)
        {
            // 检查控制器或动作上是否有 AllowAnonymous 属性
            var isAllowAnonymous = actionDescriptor.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), inherit: false).Any() || actionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), inherit: false).Any();
            if (isAllowAnonymous)
                return;
        }

        var requestPath = context.HttpContext.Request.Path;
        List<PathString> allowAnonymous = new() { "/auth", "/user" };
        if (allowAnonymous.Any(path => requestPath.StartsWithSegments(path, StringComparison.OrdinalIgnoreCase)))
            return;

        ClaimsPrincipal user = context.HttpContext?.User ?? new();
        if (!user?.Identity?.IsAuthenticated ?? false)
        {
            context.Result = new RedirectResult("/auth/login");
            return;
        }

        //bool isAdmin = user?.Claims.Any(c => c.Type == ClaimConst.CLAINM_ISADMIN && c.Value == "true") ?? false;
        //if (isAdmin) return;

        //List<PathString> adminPaths = new() { "/logdiff", "/logex", "/logop", "/logvis", };
        //if (adminPaths.Any(path => requestPath.StartsWithSegments(path, StringComparison.OrdinalIgnoreCase)))
        //{
        //    if (!user!.IsInRole("Admin"))
        //    {
        //        context.HttpContext!.Response.StatusCode = 403;
        //        context.Result = new RedirectToActionResult("index", "home", new { });
        //        return;
        //    }
        //}

        //List<PathString> superAdminPaths = new() { "/user", "/config", "/dicttyp", "/role", "/menu", };
        //if (superAdminPaths.Union(adminPaths).Any(path => requestPath.StartsWithSegments(path, StringComparison.OrdinalIgnoreCase)))
        //{
        //    if (!user!.IsInRole("SuperAdmin"))
        //    {
        //        context.HttpContext!.Response.StatusCode = 403;
        //        context.Result = new RedirectToActionResult("index", "home", new { });
        //        return;
        //    }
        //}
    }
}
